﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MMOArpgServer.DAL;
using System.Runtime.InteropServices;
using MMOArpgServer.Tool;
namespace MMOArpgServer
{

    class Program
    {
        #region 通过控制台输入ctrl+c关闭控制台
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
        extern static IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);
        [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
        extern static IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);

        static void OnClickCloseBtn()
        {

            IntPtr windowHandle = FindWindow(null, "MMOArpgServer");
            IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
            uint SC_CLOSE = 0xF060;
            RemoveMenu(closeMenu, SC_CLOSE, 0x0);
        }

        private static void CloseConsole(object sender, ConsoleCancelEventArgs e)
        {
            CacheFactory.Release();
        }
        #endregion
        
        #region 通过关闭按钮关闭控制台
        public delegate bool ControlCtrlDelegate(int ctrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate handlerRoutine, bool add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);

        private static bool HandlerRoutine(int ctrlType)
        {
            switch (ctrlType)
            {
                case 0:
                    Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭  
                    break;

                case 2:
                    Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭  
                    break;
            }
            CacheFactory.Release();
            return false;
        }

        #endregion

     
        public static void Main(string[] args)
        {

            Console.Title = "MMOArpgServer";
            //OnClickCloseBtn();
            //Console.CancelKeyPress += new ConsoleCancelEventHandler(CloseConsole);
            SetConsoleCtrlHandler(cancelHandler, true);
            LitJson.JsonData configJson = LitJson.JsonMapper.ToObject(ReadConfigFiles.GetFilesContent());
            Console.WriteLine("Starting..."+ configJson["ip"]);
            string ip = configJson["ip"].ToString();
            int port = int.Parse(configJson["port"].ToString());
            Net.ServerBase serverBase = new Net.ServerBase(ip, port);
            Console.ReadLine();
        }
    }
}
